package com.bnz.service.impl;

import com.alibaba.fastjson.JSON;
import com.bnz.Entity.User;
import com.bnz.dao.UserDao;
import com.bnz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;

/**
 * @author xy
 * @date 2022/10/27
 */
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public List<User> findAll() {
        String userJ = stringRedisTemplate.opsForValue().get("user");
        List<User> users = JSON.parseArray(userJ,User.class);
        if (users ==null || users.size() == 0){
            users = userDao.findAll();
            stringRedisTemplate.opsForValue().set("user",JSON.toJSONString(users));
        }
        return users;
    }

    @Override
    public void add(User user) {
        stringRedisTemplate.delete("user");
        userDao.save(user);
    }

    @Override
    public void updata(User user) {
        stringRedisTemplate.delete("user");
        userDao.save(user);
    }

    @Override
    public void delete(Integer id) {
        stringRedisTemplate.delete("user");
        userDao.deleteById(id);
    }
}
